<?php

/**
 * 报名，再次报名
 * User: huy
 * Date: 2016/7/5
 * Time: 21:12
 */
class IssignControl extends Control{
    private $time1    = '2016-07-20 00:00:00';   //开始
    private $time2    = '2016-08-01 00:00:00';   //中间投票时间
    private $time3    = '2016-08-31 23:59:59';   //结束
    private $hcoin    = 0;
    private $gamecoin = 2000;//投票每一票消耗的游戏币5000
    private $limit    = 10;   //每天最多投10票
    private $level    = 30;//参加活动的等级限制

    //构造函数
    function __construct(){
        parent::__construct();
        $this->actName = '新炫舞宝贝评选';
        load_config('commonMain/onload');
        $this->zone_arr = get_dmz_game_zone();
        load_model(ACT_NAME . '/main');   //自己的main.mod
        $this->model = new MainModel();

        //重新设置活动时间（用于外网、预发布环境）
        if(file_exists(APPLICATION_ROOT . '/config/basic.cfg.php')){
            //include文件的路径，$BasicCFG就存下了.php return 的数组
            $BasicCFG = include_once APPLICATION_ROOT . '/config/basic.cfg.php';
            if(!empty($BasicCFG[YEAR][ACT]['time1']) && !empty($BasicCFG[YEAR][ACT]['time2']) && !empty($BasicCFG[YEAR][ACT]['time3']) && !empty($BasicCFG[YEAR][ACT]['level']) && !empty($BasicCFG[YEAR][ACT]['gamecoin']) && !empty($BasicCFG[YEAR][ACT]['money'])){
                $this->time1    = $BasicCFG[YEAR][ACT]['time1'];
                $this->time2    = $BasicCFG[YEAR][ACT]['time2'];
                $this->time3    = $BasicCFG[YEAR][ACT]['time3'];
                $this->level    = $BasicCFG[YEAR][ACT]['level'];
                $this->gamecoin = $BasicCFG[YEAR][ACT]['gamecoin'];
                $this->money    = $BasicCFG[YEAR][ACT]['money'];
            }
        }
    }
    //报名条件
    //报名限制条件
    /*
     * 1.【任意大区】的等级≥30级
    * 2.一个账号只报名一次
    * 3.2次审核未通过，不能报名
    * 4.必填信息都填写正确&&完整
    * 5.年满16岁
    */
    //save报名
    public function save_sign($login, $uin, $zoneid){
        //		$sjmp=DOMAIN_URL.'/index.php?a=sign';   //success_jump
        $fjmp    = DOMAIN_URL . '/index.php?a=sign';   //faild_jump
        $jumpto2 = DOMAIN_URL . '/index.php?a=sign';

        //时间，登录，重复报名，等级
        $con = $this->_sign_condition($login, $uin, $zoneid);

        //前几项不满足
        if(3 > $con['success']){
            //<3：其他的报名条件：等级，报名次数...不满足
            $this->_alertMsg($con['msg'], $fjmp);
            exit;
        }

        //其他条件满足，用户信息输入
        if(3 == $con['success']){

            //图片出错返回信息
            $_SESSION['picMsg'] = '';

            $real_name = isset($_POST['real_name']) ? trim($_POST['real_name']) : '';
            if(!preg_match('/^[\x{2E80}-\x{9FFF}]{2,9}$/u', $real_name)){
                $this->_alertMsg('姓名不合法', $fjmp);
                exit;
            }
            $age = isset($_POST['age']) ? intval($_POST['age']) : 0;
            if($age < 16 || $age > 100){
                $this->_alertMsg('年龄不合法', $fjmp);
                exit;
            }
            //照片
            $pic1 = $this->_pic_up(1);
            if($pic1['stu'] > 0){
                $picMsg = '游戏截图：' . $pic1['msg'];
                $picMsg = urlencode($picMsg);
                header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                //echo 'Error---gamePic is too big '.$_SESSION['picMsg'];
                exit;
            }
            $pic2 = $this->_pic_up(2);
            if($pic2['stu'] > 0){
                //$this->_alertMsg('生活照一：'.$pic2['msg'],$fjmp);
                $picMsg = '生活照一：' . $pic2['msg'];
                //	$_SESSION['picMsg'] = $picMsg;
                $picMsg = urlencode($picMsg);
                header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                exit;
            }
            $pic3 = $this->_pic_up(3);
            if($pic3['stu'] > 0){
                //$this->_alertMsg('生活照二：'.$pic3['msg'],$fjmp);
                $picMsg = '生活照二：' . $pic3['msg'];
                //	$_SESSION['picMsg'] = $picMsg;
                $picMsg = urlencode($picMsg);
                header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                exit;
            }

            $qq = isset($_POST['qq']) ? intval($_POST['qq']) : 0;
            if(!preg_match('/^[1-9]\d{5,13}$/', $qq)){
                $this->_alertMsg('qq号不合法', $fjmp);
                exit;
            }
            $brand = isset($_POST['brand']) ? trim($_POST['brand']) : '';
            if(preg_match('/^[a-zA-Z]+$/',$brand)){  //[a-z]/i
                $this->_alertMsg('参赛宣言不能有字母', $fjmp);
                exit;
            }
            if(50 < $this->_strlen_utf8($brand) || $this->_strlen_utf8($brand)<=0){
                $this->_alertMsg('参赛宣言不能超过50字并且必须填写', $fjmp);
                exit;
            }
            $brand = mysql_real_escape_string($brand);

            $vip        = 0;    //是否vip
            $vip_status = 0;     //vip等级
            $ret        = $this->_get_roleinfo();
            if($ret){
                $vip        = $ret['lv'];
                $vip_status = $ret['status'];
            }

            //输入合法，写报名表
            $param = array(
                'uin'         => $uin,
                'zone_id'     => $zoneid,
                'account'     => $_SESSION['LoginUser'],
                'role_name'   => $_SESSION['RoleName'],
                'vip'         => $vip,
                'vip_status'  => $vip_status,
                'sex'         => $_SESSION['Gender'],
                'real_name'   => $real_name,
                'age'         => $age,
                'pic1'        => $pic1['msg'],
                'pic2'        => $pic2['msg'],
                'pic3'        => $pic3['msg'],
                'qq'          => $qq,
                'brand'       => $brand,
                'status'      => 1,
                'create_time' => date("Y-m-d H:i:s")
            );
            $this->model->insert_data('bbpx2016_userinfo', $param);
            $this->_alertMsg('亲，已成功提交报名资料。', $fjmp);      //跳到页面三 ：资料审核中...
            exit;
        }
    }

    public function sign($login, $uin){
        $view['f'] = 1;
        if($login == 1){  //已登录
            $list = $this->model->get_item('bbpx2016_userinfo', "uin,`status`", " uin={$uin}  limit 1");
            if(!empty($list)){
                //userinfo表中有该用户的记录
                $view['f'] = 2;
                $row       = $list[0];
                if(2 == $row['status']){   //报名失败一次
                    $html = <<<EOT
					<div class="signFail1" style="display:block;">
				<a class="signFail1Btn"  href="index.php?a=resign"></a>
			</div>
EOT;
                }elseif(5 == $row['status']){  //审核通过，报名成功
                    $html = <<<EOT
				<div class="signSuccess" style="display:block;">
				<a class="signSuccessBtn"  href="index.php?a=userinfo"></a>
			</div>
EOT;
                }elseif(4 == $row['status']){   //报名失败两次
                    $html = <<<EOT
			 <div class="signFail2" style="display:block;" >
				<a class="signFail2Btn"  href="index.php?a=ranking"></a>
			</div>
EOT;
                }else{  //审核中
                    $html = <<<EOT
				    <div class="signAudit" style="display:block;">
			</div>
EOT;
                }
            }
        }else{
            //未登录
            $view['f'] = 3;
        }

        //$view['f']=1   已登录，未报名
        //$view['f']=2   已登录，已报名
        //$view['f']=3  未登录

        $view['html'] = isset($html) ? $html : '';
        load_view(ACT_NAME . '/sign', $view);
    }

    //重新报名
    public function resign($login, $uin){
        if($login == 1){
            $view['f'] = 2;
            $list      = $this->model->get_item('bbpx2016_userinfo', "uin,`status`", " uin={$uin}  limit 1");
            if(!empty($list) && 2 == $list[0]['status']){
                $info = $this->model->get_item('bbpx2016_userinfo', "account,real_name,age,role_name,zone_id,qq,brand", " uin={$uin}  limit 1");
                $zones = get_dmz_game_zone();
                $view['zone_name']=$zones[$info[0]['zone_id']];
                $view['info']=$info[0];
                //status=2   未通过，重新报名
                load_view(ACT_NAME . '/resign', $view);
                exit;
            }
        }else{
            $view['f'] = 3;
        }
        header('Location:' . DOMAIN_URL . '/?a=resign', $view);   //填信息的报名页面
    }

    //重新报名
    public function resave_sign($login, $uin, $zoneid){
        $fjmp    = DOMAIN_URL . '/index.php?a=sign';
        $jumpto2 = DOMAIN_URL . '/index.php?a=resign';
        $con     = $this->_sign_condition($login, $uin, $zoneid); //判断报名条件
        if(3 > $con['success']){
            $this->_alertMsg($con['msg'], $fjmp);
            exit;
        }

        //前几个条件：时间，登录，等级  满足
        if(3 == $con['success']){
            $list = $this->model->get_item('bbpx2016_userinfo', "uin,`status`", " uin={$uin} limit 1");
            if(!empty($list) && 2 == $list[0]['status']){
                //status =2     审核失败，重新报名，上传图片

                //照片
                $pic1 = $this->_pic_up(1);
                if($pic1['stu'] > 0){
                    $picMsg = '游戏截图：' . $pic1['msg'];
                    $picMsg = urlencode($picMsg);
                    header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                    exit;
                }
                $pic2 = $this->_pic_up(2);
                if($pic2['stu'] > 0){
                    $picMsg = '生活照一：' . $pic2['msg'];
                    $picMsg = urlencode($picMsg);
                    header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                    exit;
                }
                $pic3 = $this->_pic_up(3);
                if($pic3['stu'] > 0){
                    $picMsg = '生活照二：' . $pic3['msg'];
                    $picMsg = urlencode($picMsg);
                    header("Location:" . $jumpto2 . '&picMsg=' . $picMsg);
                    exit;
                }
                $this->model->update_data('bbpx2016_userinfo', array(
                    'pic1'   => $pic1['msg'],
                    'pic2'   => $pic2['msg'],
                    'pic3'   => $pic3['msg'],
                    'status' => 3
                ), "uin={$uin} limit 1");
                $this->_alertMsg('亲，恭喜您二次提交报名资料成功。', $fjmp);
                exit;
            }
        }
        header('Location:' . DOMAIN_URL . '/?a=sign');
    }

    //报名——前提条件控制：时间，登录，重复报名，等级
    public function _sign_condition($login, $uin, $zoneid){
        $result = array('success' => 1);
        $time   = time();
        if($time < strtotime($this->time1)){
            $result['msg'] = '亲~本次活动尚未开始哦';
            return $result;
        }
        if($time > strtotime($this->time3)){
            $result['msg'] = '亲~本活动已结束~更多精彩活动请关注官网活动专区';
            return $result;
        }
        if($login == 0){   //等于1表示没有登录了
            $result['success'] = 2;
            $result['msg']     = '亲，还没有登录哦';
            return $result;
        }
        $list = $this->model->get_item('bbpx2016_userinfo', 'uin', " uin={$uin} and `status`<>2");
        //status=2表示还可以进行报名
        if(!empty($list)){
            $result['msg'] = '亲，每个帐号只能报名1次，不能重复报名。';
            return $result;
        }
        //$this->_level_condition()满足返回:true
        //if($_SESSION['Level']<$this->level)
        if(false == $this->_level_condition($uin, $zoneid)){
            $result['msg'] = '亲，您游戏等级未达到30级，还不能报名哦~需达到30级才可参与本活动';
            return $result;
        }
        $result['success'] = 3;
        return $result;
    }

    //判断等级条件

    public function _level_condition($uin, $zoneid){
        load_extend('PromoterBill');
        $gm_server = new gm_server();
        $response  = $gm_server->getUserGameInfo($uin, 0, '', 0, $zoneid);
        if($response && $response->nErrorCode == 0){
            $this->sex       = $response->stPublicInfo->gender;
            $this->role_name = $response->stPublicInfo->szRoleName;
            return $response->stPublicInfo->nLevel >= $this->level ? true : false;
        }else{
            return false;
        }
    }

    //计算多少个字数    ord()计算汉字的assII值
    public function _strlen_utf8($str){
        if(function_exists('mb_strlen')){
            return mb_strlen($str, 'utf8');
        }
        $i     = 0;
        $count = 0;
        $len   = strlen($str);
        while($i < $len){
            $chr = ord($str[$i]);
            $count++;
            $i++;
            if($i >= $len){
                break;
            }

            if($chr & 0x80){
                $chr <<= 1;
                while($chr & 0x80){
                    $i++;
                    $chr <<= 1;
                }
            }
        }
        return $count;
    }

    //获取角色数据，$reload=true 时获取最新数据
    function _get_roleinfo(){
        load_extend('PromoterBill');
        $gm_server = new gm_server();
        $response  = $gm_server->getUserGameInfo($_SESSION['UIN'], 0, '', 0, $_SESSION[DOMAIN_ACT_ZONEID_KEY]);
        if($response && $response->nErrorCode == 0){
            $ret['lv']       = $response->nVipLevel;
            $ret['RoleName'] = $_SESSION['RoleName'] = $response->stPublicInfo->szRoleName;
            $ret['money']    = $_SESSION['money'] = $response->stPrivateInfo->nMoney;
            $stratTime       = $response->nVipstratTime;
            $EffiectDays     = $response->nVipEffiectDays;
            if($stratTime + $EffiectDays * 86400 >= time()){
                $ret['status'] = 1;
            }else{
                $ret['status'] = 0;
            }
            return $ret;
        }
        return false;
    }

    //图片上传
    public function _pic_up($i){
        load_helper('upload2fs');
        return uploadImg('pic' . $i, 1024000);
    }

    //弹出消息
    public function _alertMsg($msg, $jumpto){
        header("content-type:text/html; charset=utf-8");
        echo "<script>alert('" . $msg . "');</script>";
        echo "<script>self.location=\"$jumpto\"</script>";
        exit;
    }
}